<script setup>
import { ref, computed, onMounted } from 'vue'
import Toolbar from './components/Toolbar.vue'
import DownloadList from './components/DownloadList.vue'
import DetailsPanel from './components/DetailsPanel.vue'
import StatusBar from './components/StatusBar.vue'
import Sidebar from './components/Sidebar.vue'
import HttpSettings from './components/HttpSettings.vue'
import BtSettings from './components/BtSettings.vue'
import SystemSettings from './components/SystemSettings.vue'
import SettingsModal from './components/SettingsModal.vue'
import AddTaskModal from './components/AddTaskModal.vue'
import Help from './components/Help.vue'
import * as Manager from '../wailsjs/go/main/Manager.js'
import { EventsOn } from '../wailsjs/runtime/runtime.js'
import { faPlus, faPlay, faPause, faTrash, faCheckDouble, faUpDown, faQuestion, faDownload, faHourglassStart, faCheck, faGear, faGears, faSliders } from '@fortawesome/free-solid-svg-icons'

const selectedMenu = ref('downloading'); // 默认显示正在下载
const tasks = ref([])
const selectedId = ref('')
const selectedTask = ref(null)
const allSelected = ref(false)
const showDetails = ref(false)
const showHelpPage = ref(false)
const showSettings = ref(false)
const showAddModal = ref(false)
const selectedCategory = ref('')
const settings = ref({
  savePath: '',
  maxConcurrent: 3,
  speedLimitKBs: 0,
  proxy: '',
  lang: 'zh-CN',
})

async function onAddTask({ url, path, filename, category }) {
  try {
    const u = String(url || '').trim()
    if (!u) return
    // 磁力链接走 BT 添加
    if (u.startsWith('magnet:')) {
      await Manager.AddMagnet(u, category || '')
      await refresh()
      return
    }
    // 普通 HTTP/HTTPS
    const finalFilename = filename || u.split('/').pop().split('?')[0]
    const savePath = `${path}/${finalFilename}`
    await Manager.Add(u, savePath)
    await refresh()
  } catch (error) {
    console.error('添加任务失败:', error)
  }
}

async function refresh() {
  try {
    let list = []
    if (selectedCategory.value) {
      list = await Manager.ListByCategory(selectedCategory.value)
    } else {
      list = await Manager.List()
    }
    tasks.value = list
    if (selectedId.value) {
      selectedTask.value = list.find(t => t.id === selectedId.value) || null
    }
  } catch (e) {
    console.error(e)
  }
}

onMounted(async () => {
  // load tasks and settings
  refresh()
  try {
    const s = await Manager.GetSettings()
    settings.value = s
  } catch (e) { console.error(e) }
  EventsOn('tasks:update', () => {
    refresh()
  })
})

async function onAdd(){
  showAddModal.value = true;
  // showSettings.value = true
  // const url = window.prompt('输入下载 URL:')
  // if (!url) return
  // await Manager.Add(url)
}
async function onAddAdv(){
  const url = window.prompt('输入下载 URL:')
  if (!url) return
  let suggest = 'download.bin'
  try { const u = new URL(url); const base = u.pathname.split('/').pop(); if (base) suggest = base }
  catch {}
  const save = await Manager.PickSavePath(suggest)
  if (!save) return
  const category = window.prompt('分类(可选):') || ''
  await Manager.AddWithOptions(url, save, category)
}
async function onAddMagnet(){
  const magnet = window.prompt('输入磁力链接(magnet:...):')
  if (!magnet) return
  const category = window.prompt('分类(可选):') || ''
  await Manager.AddMagnet(magnet, category)
}
async function onAddTorrent(){
  const p = await Manager.PickTorrentPath()
  if (!p) return
  const category = window.prompt('分类(可选):') || ''
  await Manager.AddTorrentPath(p, category)
}
async function onPause(){
  if (allSelected.value) { await onPauseAll(); return }
  if (!selectedId.value) return
  await Manager.Pause(selectedId.value)
}
async function onResume(){
  if (allSelected.value) { await onResumeAll(); return }
  if (!selectedId.value) return
  await Manager.Resume(selectedId.value)
}
async function onRemove(){
  if (allSelected.value) {
    if (!confirm('确定要删除所有任务吗？此操作不可恢复。')) return
    for (const t of tasks.value) {
      try { await Manager.Remove(t.id) } catch (e) { console.error(e) }
    }
    allSelected.value = false
    selectedId.value = ''
    selectedTask.value = null
    await refresh()
    return
  }
  if (!selectedId.value) return
  await Manager.Remove(selectedId.value)
  selectedId.value = ''
  selectedTask.value = null
}
function onSelect(id) {
  allSelected.value = false
  selectedId.value = id
  selectedTask.value = tasks.value.find(t => t.id === id) || null
}

function onShowDetails(id) {
  onSelect(id)
  showDetails.value = true
}

function onMenuSelected(menu){
  selectedMenu.value = menu
  // 切换到设置页时隐藏详情
  if (menu === 'http-settings' || menu === 'bt-settings' || menu === 'system-settings') {
    showDetails.value = false
  }
  // 切换菜单时关闭帮助页，回到对应面板
  showHelpPage.value = false
}

function onSaveHttpSettings(patch){
  settings.value = { ...settings.value, ...patch }
}
function onSaveBtSettings(patch){
  settings.value = { ...settings.value, ...patch }
  try { Manager.UpdateSettings && Manager.UpdateSettings(settings.value) } catch(e) { console.error(e) }
}
function onSaveSystemSettings(patch){
  settings.value = { ...settings.value, ...patch }
}

function onCategory(cat){
  selectedCategory.value = cat || ''
  refresh()
}

async function onSetCategory(cat){
  if (!selectedId.value) return
  try { await Manager.SetCategory(selectedId.value, cat || '') } catch(e){ console.error(e) }
  refresh()
}

const canPause = computed(() => {
  if (allSelected.value) return tasks.value.some(t => t.status === 'downloading')
  return !!selectedTask.value && selectedTask.value.status === 'downloading'
})
const canResume = computed(() => {
  if (allSelected.value) return tasks.value.some(t => t.status === 'paused' || t.status === 'waiting')
  return !!selectedTask.value && (selectedTask.value.status === 'paused' || selectedTask.value.status === 'waiting')
})
const canRemove = computed(() => {
  if (allSelected.value) return tasks.value.length > 0
  return !!selectedTask.value
})

async function onSaveSettings(v){
  settings.value = v
  try { await Manager.UpdateSettings(v) } catch (e) { console.error(e) }
  showSettings.value = false
}

async function onPauseAll() {
  try {
    await Manager.PauseAll()
  } catch (e) { 
    console.error('Failed to pause all:', e)
  }
}

async function onResumeAll() {
  try {
    await Manager.ResumeAll()
  } catch (e) {
    console.error('Failed to resume all:', e)
  }
}

async function onClearCompleted() {
  try {
    await Manager.ClearCompleted()
  } catch (e) {
    console.error('Failed to clear completed:', e)
  }
}

// Add computed properties to control button states
const hasActiveOrWaiting = computed(() => {
  return tasks.value.some(t => t.status === 'downloading' || t.status === 'waiting')
})

const hasPausedOrFailed = computed(() => {
  return tasks.value.some(t => t.status === 'paused' || t.status === 'failed')
})

const hasCompleted = computed(() => {
  return tasks.value.some(t => t.status === 'completed')
})
// Search query
const searchQuery = ref('')

// Handle menu selection from Sidebar
const handleMenuSelected = (menu) => {
  // Update your filtering logic here if needed
  console.log('Selected menu:', menu);
  selectedMenu.value = menu;
}

// 排序设置
const sortKey = ref('name') // name | speed | size
const sortOrder = ref('asc') // asc | desc

function onToggleSort(){
  // 轮换排序键并切换顺序
  sortKey.value = sortKey.value === 'name' ? 'speed' : (sortKey.value === 'speed' ? 'size' : 'name')
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
}

function onShowHelp(){
  // 暂用设置面板作为帮助
  showSettings.value = true
}

function onSelectAll(){
  allSelected.value = true
  selectedId.value = ''
  selectedTask.value = null
}

// 根据选择的菜单和搜索查询过滤任务并排序
const filteredTasks = computed(() => {
  const list = tasks.value.filter(task => {
    // 根据菜单选择过滤
    if (selectedMenu.value === 'downloading' && 
        !['downloading', 'paused', 'waiting'].includes(task.status)) {
      return false
    }
    if (selectedMenu.value === 'waiting' && task.status !== 'waiting') {
      return false
    }
    if (selectedMenu.value === 'completed' && !['completed','paused','failed'].includes(task.status)) {
      return false
    }
    
    // 根据搜索关键词过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      return task.name.toLowerCase().includes(query) || 
             (task.url && task.url.toLowerCase().includes(query))
    }
    
    return true
  })
  const arr = list.slice()
  const key = sortKey.value
  const order = sortOrder.value
  arr.sort((a, b) => {
    let va = a[key] ?? 0
    let vb = b[key] ?? 0
    if (key === 'name') {
      va = String(va || '').toLowerCase()
      vb = String(vb || '').toLowerCase()
      if (va < vb) return order === 'asc' ? -1 : 1
      if (va > vb) return order === 'asc' ? 1 : -1
      return 0
    }
    const na = Number(va) || 0
    const nb = Number(vb) || 0
    return order === 'asc' ? (na - nb) : (nb - na)
  })
  return arr
})

// 格式化文件大小
const formatSize = (bytes) => {
  if (!bytes) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let size = parseFloat(bytes)
  let unitIndex = 0
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`
}

// 格式化下载速度
const formatSpeed = (bytesPerSecond) => {
  if (!bytesPerSecond) return '0 B/s'
  return `${formatSize(bytesPerSecond)}/s`
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'downloading': '下载中',
    'paused': '已暂停',
    'completed': '已完成',
    'failed': '失败',
    'waiting': '等待中',
    'deleted': '已删除'
  }
  return statusMap[status] || status
}

// 计算总下载量
const totalDownloaded = computed(() => {
  return tasks.value.reduce((sum, task) => {
    return sum + (task.downloaded || 0)
  }, 0)
})

// 计算总速度
const totalSpeed = computed(() => {
  return tasks.value.reduce((sum, task) => {
    return sum + (task.speed || 0)
  }, 0)
})

// 计算活动下载数
const activeCount = computed(() => {
  return tasks.value.filter(t => t.status === 'downloading').length
})
</script>

<template>
  <div class="app">
    <!-- Main Content -->
    <div class="layout">
      <!-- Sidebar -->
      <Sidebar @menu-selected="onMenuSelected" />

      <!-- Main Panel -->
      <div class="main-panel">
        <!-- Main content switcher: task list or settings -->
        <template v-if="selectedMenu==='downloading' || selectedMenu==='waiting' || selectedMenu==='completed'">
          <!-- Toolbar Component -->
          <Toolbar
            :search-query="searchQuery"
            :can-pause="canPause"
            :can-resume="canResume"
            :can-remove="canRemove"
            :has-items="tasks.length > 0"
            :plus-icon="faPlus"
            :play-icon="faPlay"
            :pause-icon="faPause"
            :trash-icon="faTrash"
            :check-double-icon="faCheckDouble"
            :up-down-icon="faUpDown"
            :question-icon="faQuestion"
            @update:searchQuery="val => (searchQuery = val)"
            @add="() => (showAddModal = true)"
            @pause="onPause"
            @resume="onResume"
            @remove="onRemove"
            @check-double="onSelectAll"
            @toggle-sort="onToggleSort"
            @show-help="() => { showHelpPage = !showHelpPage; if (showHelpPage) showDetails = false }"
          />

          <!-- Download List Component or Help Page -->
          <Help v-if="showHelpPage" />
          <DownloadList v-else
            :items="filteredTasks"
            :selected-id="selectedId"
            @select="onSelect"
            @pause="onPause"
            @resume="onResume"
            @remove="onRemove"
            @details="onShowDetails"
          />

          <!-- Details Panel Component -->
          <DetailsPanel
            v-if="showDetails && selectedTask && !showHelpPage"
            :task="selectedTask"
            :settings="settings"
            @set-category="onSetCategory"
            @close="showDetails = false"
          />
        </template>
        <template v-else>
          <HttpSettings v-if="selectedMenu==='http-settings'" :settings="settings" @save-settings="onSaveHttpSettings" />
          <BtSettings v-else-if="selectedMenu==='bt-settings'" :settings="settings" @save-settings="onSaveBtSettings" />
          <SystemSettings v-else :settings="settings" @save-settings="onSaveSystemSettings" />
        </template>

        <!-- Status Bar Component (hide on settings/help) -->
        <StatusBar v-if="(selectedMenu==='downloading' || selectedMenu==='waiting' || selectedMenu==='completed') && !showHelpPage"
          :total-downloaded="totalDownloaded"
          :total-speed="totalSpeed"
          :active-count="activeCount"
          :has-active-or-waiting="hasActiveOrWaiting"
          :has-paused-or-failed="hasPausedOrFailed"
          :has-completed="hasCompleted"
          @pause-all="onPauseAll"
          @resume-all="onResumeAll"
          @clear-completed="onClearCompleted"
        />
      </div>
    </div>

    <AddTaskModal 
      v-if="showAddModal"
      :default-path="settings.savePath"
      @add="onAddTask"
      @close="showAddModal = false"
    />

    <!-- Settings Modal -->
    <SettingsModal
      v-if="showSettings"
      v-model="settings"
      @save="onSaveSettings"
      @close="showSettings = false"
    />
  </div>
</template>

<style>
:root {
  --primary-color: #e5c41e;
  --danger-color: #f44336;
  --success-color: #4caf50;
  --warning-color: #ff9800;
  --bg-color: #263238;
  --card-bg: #37474f;
  --text-color: #e0e0e0;
  --text-secondary: #a0a0a0;
  --border-color: #455a64;
  --hover-bg: rgba(255, 255, 255, 0.05);
  --active-bg: rgba(255, 255, 255, 0.1);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

body, html, #app {
  height: 100%;
  overflow: hidden;
}

.app {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--bg-color);
  color: var(--text-color);
}

/* Layout container: sidebar + main panel side-by-side */
.layout {
  display: flex;
  flex: 1;
  min-height: 0; /* allow children to overflow:auto properly */
  overflow: hidden;
}

/* Top Navigation */
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 48px;
  background-color: #1e88e5;
  color: white;
  padding: 0 16px;
  -webkit-app-region: drag;
}

.logo {
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 48px;
  background-color: #1e88e5;
  color: white;
  padding: 0 16px;
  -webkit-app-region: drag;
}

.nav-right {
  display: flex;
  align-items: center;
  height: 100%;
}

.nav-item {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 16px;
  cursor: pointer;
  -webkit-app-region: no-drag;
  transition: background-color 0.2s;
}

.nav-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.nav-item .icon {
  margin-right: 8px;
}

/* Main Content */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* Sidebar styles are now in Sidebar.vue */

/* Main Panel */
.main-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 16px;
  min-height: 0; /* critical for inner scroll areas like .list-body */
}

/* Toolbar */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.toolbar-left, .toolbar-right {
  display: flex;
  gap: 8px;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn:hover:not(:disabled) {
  background-color: var(--hover-bg);
}

.btn:active:not(:disabled) {
  background-color: var(--active-bg);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn.primary {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.btn.primary:hover:not(:disabled) {
  background-color: #1565c0;
}

.btn.danger {
  background-color: var(--danger-color);
  color: white;
  border-color: var(--danger-color);
}

.btn.danger:hover:not(:disabled) {
  background-color: #d32f2f;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-box input {
  padding: 6px 12px 6px 32px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  width: 200px;
  font-size: 14px;
  background-color: var(--card-bg);
  color: var(--text-color);
}

.search-icon {
  position: absolute;
  left: 8px;
  color: var(--text-secondary);
  pointer-events: none;
}

/* Download List */
.download-list {
  flex: 1;
  background-color: var(--card-bg);
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.list-header, .list-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr auto;
  align-items: center;
  padding: 12px 16px;
  gap: 16px;
}

.list-header {
  font-weight: 500;
  background-color: #263238;
  border-bottom: 1px solid var(--border-color);
  color: var(--text-secondary);
  font-size: 14px;
}

.list-body {
  flex: 1;
  overflow-y: auto;
}

.list-item {
  position: relative;
  cursor: pointer;
  transition: background-color 0.2s;
}

.list-item:hover {
  background-color: var(--hover-bg);
}

.list-item.active {
  background-color: rgba(30, 136, 229, 0.2);
}

.col-name {
  display: flex;
  align-items: center;
  overflow: hidden;
}

.file-icon {
  margin-right: 8px;
  flex-shrink: 0;
}

.file-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.downloading {
  background-color: #0d47a1;
  color: #bbdefb;
}

.status-badge.completed {
  background-color: #1b5e20;
  color: #a5d6a7;
}

.status-badge.paused, .status-badge.waiting {
  background-color: #827717;
  color: #e6ee9c;
}

.status-badge.failed {
  background-color: #bf360c;
  color: #ffccbc;
}

.progress-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #455a64;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: var(--primary-color);
  transition: width 0.3s;
}

/* Status Bar */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background-color: #1a2327;
  border-top: 1px solid var(--border-color);
  font-size: 12px;
  color: var(--text-secondary);
  margin-top: 8px;
  border-radius: 4px;
}

.status-left {
  display: flex;
  gap: 16px;
}

.status-right {
  display: flex;
  gap: 8px;
}

/* Scrollbar */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #1e272c;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #455a64;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #546e7a;
}
</style>
